
#import "GeometryAppDelegate.h"
#import "ContentsController.h"
#import "UnitConverterTableViewController.h"


UITabBarController *tabBarControllerRef;
/////////////////////////////////////////////
//  GeometryAppDelegate class implementation
//     UIApplicationDelegate Protocol:
//        -(void) applicationDidFinishLaunching:(UIApplication *);
//        -(void) applicationWillTerminate:(UIApplication *);
//
//     Getters:
//        -(NSManagedObjectContext *) managedObjectContext;
//        -(NSManagedObjectModel *) managedObjectModel;
//        -(NSPersistentStoreCoordinator *) persistentStoreCoordinator;
//
//     Private helper:
//        -(NSString *) applicationDocumentsDirectory;
//
//     Public Override NSObject:
//        -(void) dealloc
/////////////////////////////////////////////
@implementation GeometryAppDelegate

/**
 * synthesize getters & setters for window and ViewControllers
 */
@synthesize window;
@synthesize tabBarController;
@synthesize contentsController;

/////////////////////////////////////////////
-(void)applicationDidFinishLaunching:(UIApplication *)application {

  /**
   * open database
   */
  contentsController.managedObjectContext = [self managedObjectContext];

  NSArray *viewC = [tabBarController viewControllers];
  NSLog(@"---->%p, %d", [tabBarController view], [viewC count]);
  /* assign tabBarController view's delegate to window delegate */
  [window addSubview:tabBarController.view];
  [window makeKeyAndVisible];
  tabBarControllerRef = tabBarController;
}


/**
 * it will not be used by 
 *
 * applicationWillTerminate: saves changes in the 
 * application's managed object context 
 * before the application terminates.
 */
/////////////////////////////////////////////
-(void)applicationWillTerminate:(UIApplication *)application {

  /**
   * save updated data. It will not be used by Geometry
   */  
  NSError *error;
  if( managedObjectContext != nil ) {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
    /*
    Replace this implementation with code to handle the error appropriately.
    
    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
    */
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    } 
  }
}



/////////////////////////////////////////////
//  Getters for core data
/////////////////////////////////////////////
#pragma mark -
#pragma mark Core Data stack

/**
 * managedObjectContext getter
 * Returns the managed object context for the application.
 * If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
/////////////////////////////////////////////
-(NSManagedObjectContext *) managedObjectContext {
  
  /* if it has configed return */  
  if( self->managedObjectContext ) {
     return self->managedObjectContext;
  }
  

  /* set managedObjectContex */
  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  if( coordinator != nil ) {
     self->managedObjectContext = [NSManagedObjectContext new];
     [self->managedObjectContext setPersistentStoreCoordinator: coordinator];
  }

  return self->managedObjectContext;
}

/**
 * getter
 * Returns the managed object model for the application.
 * If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
/////////////////////////////////////////////
-(NSManagedObjectModel *) managedObjectModel {
  
  if (self->managedObjectModel != nil) {
    return self->managedObjectModel;
  }
 
  self->managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];  
  return self->managedObjectModel;
}


/**
 * getter
 * Returns the persistent store coordinator for the application.
 * If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
/////////////////////////////////////////////
-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {
  
  if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
  }
    
  /**
   * Get the sqlite database path
   */
  NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Geometry-Triangle.sqlite"];

  /*
   Set up the store.
   For the sake of illustration, provide a pre-populated default store.
   */
  NSFileManager *fileManager = [NSFileManager defaultManager];

  // If the expected store doesn't exist, copy the default store.
  if( ![fileManager fileExistsAtPath:storePath] ) {
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Geometry-Triangle" ofType:@"sqlite"];
    if( defaultStorePath ) {
      [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
  }
  
  NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
  
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

  NSError *error;
  if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                                configuration:nil 
                                                          URL:storeUrl 
                                                      options:nil 
                                                        error:&error]) {
  /*
  Replace this implementation with code to handle the error appropriately.
  
  abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  
  Typical reasons for an error here include:
  * The persistent store is not accessible
  * The schema for the persistent store is incompatible with current managed object model
  Check the error message to determine what the actual problem was.
  */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }  
    
  return persistentStoreCoordinator;
}


#pragma mark -
#pragma mark Application's documents directory


/**
 * private method.
 * Returns the path to the application's documents directory.
 */
/////////////////////////////////////////////
-(NSString *) applicationDocumentsDirectory {
  return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management
/////////////////////////////////////////////
-(void)dealloc {
  [managedObjectContext release];
  [managedObjectModel release];
  [persistentStoreCoordinator release];
  
  [contentsController release];
  [tabBarController release];
  [window release];
  [super dealloc];
}

@end
